package cn.tianshi.board;

import cn.tianshi.board.bean.ApiModel;
import cn.tianshi.board.bean.Body;
import org.apache.commons.collections4.CollectionUtils;

public class CreateSql {

    public void createSql(String host, ApiModel apiModel) {
        createSysRouter(host, apiModel);
        for (Body body : apiModel.getRequestBody()) {
            createSysRouterFieldMapping(body);
        }
        for (Body body : apiModel.getResponseBody()) {
            createSysRouterFieldMapping(body);
        }
        System.out.println("UPDATE dfcw.SYS_ROUTER_FIELD_MAPPING SET DEFAULT_VALUE=NULL where DEFAULT_VALUE='null';");
    }

    private void createSysRouter(String host,ApiModel apiModel) {
        String sql = "INSERT INTO dfcw.SYS_ROUTER " +
                "(ID, REQUEST_PATH, HOST, MAPPING_PATH, HANDLER_TYPE, MAPPING_METHOD, REMARK, DEL_FLAG, LOGIN_FLAG) " +
                "VALUES('" + apiModel.getRouterId() + "','" + apiModel.getGatewayUrl() + "','" + host + "','" +
                apiModel.getCoreUrl() + "','" + apiModel.getHandlerType() + "','" + (apiModel.getMappingMethod().contains("GET")?"1":"2") +
                "','" + apiModel.getApiName() + "','" + "0" + "','" + apiModel.getLoginFlag() + "');";
        System.out.println(sql);
    }

    private void createSysRouterFieldMapping(Body body) {
        if (CollectionUtils.isNotEmpty(body.getRows())) {
            for (Body row : body.getRows()) {
                createSysRouterFieldMapping(row);
            }
        }
        String sql = "INSERT INTO dfcw.SYS_ROUTER_FIELD_MAPPING " +
        "(ID, ROUTER_ID, `TYPE`, ALIAS, OUTER_NAME, DEFAULT_VALUE, PID, REMARK, DEL_FLAG) " +
        "VALUES('" + body.getId() + "','" + body.getRouterId() + "','" + body.getType() + "','" + body.getAlias() + "','" +
                body.getOuterName() + "','" + body.getDefaultValue() + "','" + body.getPid() + "','" + body.getRemark() + "','" +
                "0');";
        System.out.println(sql);
    }
}
